const router = require('koa-router')()
const JWT = require('jsonwebtoken')
const key = 'wejknqolwe;qmwlq';
const userList = [{
  "id": "1",
  "username": "admin",
  "password": "admin",
  "nickname": "有梦想的程序员！",
  "avatar": "https://robohash.org/123?set=set5",
  "role": 'admin'
},{
  "id": "2",
  "username": "zhangsan",
  "password": "zhangsan",
  "nickname": "八两",
  "avatar": "https://robohash.org/8765?set=set4",
  "role": 'user'
}]

router.post('/login', ctx => {
  const { username, password } = ctx.request.body;

  const item = userList.find(v => v.username === username && v.password === password)


  if(item) {
    const userInfo = {
      id: item.id,
      nickname: item.nickname,
      avatar: item.avatar,
      username: item.username,
      role: item.role
    }
    ctx.body = {
      code: 200,
      msg: '登录成功， 欢迎' + item.nickname,
      data: {
        userInfo: userInfo,
        token: JWT.sign(userInfo, key)
      }
    }
  } else {
    ctx.body = {
      code: 400,
      msg: '账户密码错误， 请重新输入！'
    }
  } 

})

module.exports = router



